// packageE/pages/chooseAunt/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        translateX: 0,
        // 评价文本映射
        ratingTexts: ["非常差", "比较差", "一般", "比较好", "非常好"],
        // 客户位置（示例数据）
        centerLongitude: 121.276389,
        centerLatitude: 31.233468,
        // 地图标记点
        markers: [],
        clientLocation: {},
        // 配送员数据
        aunts: [],
        // 排序后的配送员数据
        sortedAunts: [],
        // 排序类型
        sorttype: 'distance',
        // 选中的配送员
        selectedAunt: null,
        // 侧滑窗口状态
        slidePanelOpen: false,
        // 照片预览相关
        showPhotoModal: false,
        currentAunt: null,
        currentPhotoIndex: 0,
        liechecked: false,
        type: 0,
        activeIndex: 0,
        scrollLeft: 0,
        lastScrollTime: 0,
        city: '全球',
        RatingDesc:
            [
                '未评分',
                '非常差',
                '比较差',
                '一般',
                '比较好',
                '非常好'
            ],
    },
    onScroll(e) {
        // const now = Date.now()
        // if (now - this.data.lastScrollTime > 200) {
        // //   this.playSound()
        //   this.setData({ lastScrollTime: now })
        // }
        // 计算当前居中项
        const scrollLeft = e.detail.scrollLeft
        this.setData({ scrollLeft })
    },

    selectCity(e) {
        const {city,index,latitude,longitude}=e.currentTarget.dataset;
        console.log(e);
        /*获取可视窗口宽度*/
        // var w = wx.getWindowInfo().windowWidth - 300;
        var leng = this.data.cities.length;
        // var i = e.target.dataset.index;
        var disX = (index - 1) * 270 / leng;
        let myclientLocation={};
        myclientLocation.latitude=latitude;
        myclientLocation.longitude=longitude;
        this.getNearbyAunts(myclientLocation, this.data.sorttype,city);
        this.setData({
            city,
            activeIndex: index,
            scrollLeft: disX // 根据实际item宽度调整
        })
        // this.triggerEvent('change', this.data.cities[index])
    },

    //   playSound() {
    //     const audioCtx = wx.createInnerAudioContext()
    //     audioCtx.src = '/assets/sound/scroll.mp3'
    //     audioCtx.play()
    //   },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        if (options?.type) {
            this.setData({
                type: options.type
            })
            this.GetTalentPooluniqueCitys({}).then((res) => {
                console.log(res.data)
                let mycityes = [{ city: '全球', latitude: 31.233468, longitude: 121.276389 }, ...res.data.value.uniqueCitys]
                //  res.data.value.uniqueCitys.unshift({ city: '全球', latitude: 31.233468, longitude: 121.276389 }); // arr变为[1, 2, 3]
                this.setData({
                    cities: mycityes
                })
            })
        }

        
        // if(options?.orderId){

        // }
        // debugger
        // 获取客户位置（实际项目中应通过参数传递）
        var clientLocation = {
            longitude: 121.276389,
            latitude: 31.233468
        };
        if (options?.longitude && options?.latitude) {
            clientLocation.latitude = Number(options.latitude);
            clientLocation.longitude = Number(options.longitude);
        }
        let windowWidth=wx.getWindowInfo().windowWidth;
        setTimeout(() => {
            // 设置客户位置为中心点
            this.setData({
                translateX: -windowWidth+50,
                windowWidth: windowWidth - 50,
                centerLongitude: clientLocation.longitude,
                centerLatitude: clientLocation.latitude,
                clientLocation
            });
        }, 100);

        setTimeout(() => {
            // 获取附近的配送员数据（模拟数据）
            this.getNearbyAunts(clientLocation, "distance","上海市");

        }, 200);

    },
    GetNearbyAuntsinfo(params) {
        return wx.Http.post(
            "/TalentPoolAppService/GetNearbyAunts",
            params
        );
    },
    GetTalentPooluniqueCitys(params) {
        return wx.Http.get(
            "/TalentPoolAppService/GetTalentPooluniqueCitys",
            params
        );
    },
    // 获取附近的配送员数据（模拟）
    getNearbyAunts(clientLocation, mode,city) {
        let params = {
            latitude: clientLocation.latitude,
            longitude: clientLocation.longitude,
            mode,
            city
        }
        this.GetNearbyAuntsinfo(params).then((res) => {
            if (res.data) {
                this.setData({
                    sortedAunts: res.data.value.result
                }, () => {
                    // 初始化地图标记
                    this.initMapMarkers();
                });
            }

        })

    },

    // 排序配送员数据
    sortAunts(aunts, type) {
        return [...aunts].sort((a, b) => {
            if (type === 'distance') {
                return a.distance - b.distance;
            } else if (type === 'rating') {
                return b.rating - a.rating;
            } else if (type === 'orders') {
                return b.orderCount - a.orderCount;
            }
            return 0;
        });
    },
    colorchecked(key) {
        var keyobj = {};
        switch (key) {
            case "家政":
                keyobj.color = '#d4237a';
                keyobj.iconPath = '/images/d4237a.png';
                break;
            case "普工":
                keyobj.color = '#2c2c2c';
                keyobj.iconPath = '/images/2c2c2c.png';
                break;
            case "技工":
                keyobj.color = '#1296db';
                keyobj.iconPath = '/images/1296db.png';
                break;
            case "技师":
                keyobj.color = '#d4237a';
                keyobj.iconPath = '/images/d4237a.png';
                break;
            default:
                keyobj.color = '#515151';
                keyobj.iconPath = '/images/515151.png';
                break;
        }
        return keyobj;
    },

    // 初始化地图标记
    initMapMarkers() {
        const clientMarker = {
            id: 0,
            latitude: this.data.centerLatitude,
            longitude: this.data.centerLongitude,
            iconPath: '/images/glocation.png',
            width: 30,
            height: 30,
            anchor: { x: 0.5, y: 0.5 },
            callout: {
                content: '客户位置',
                color: '#1890ff',
                borderRadius: 10,
                padding: 5,
                display: 'ALWAYS'
            }
        };
       
        const auntMarkers = this.data.sortedAunts.map(aunt => (
            {
                id: aunt.id,
                latitude: aunt.latitude,
                longitude: aunt.longitude,
                iconPath: this.colorchecked(aunt.typeOf).iconPath,
                width: 30,
                height: 30,
                anchor: { x: 0.5, y: 0.5 },
                callout: {
                    content: aunt.name + "&" + aunt.job,
                    color: this.colorchecked(aunt.typeOf).color,
                    bgColor: '#ffffff',
                    borderRadius: 10,
                    padding: 5,
                    display: 'ALWAYS'
                }
            }));
        this.setData({
            markers: [clientMarker, ...auntMarkers]
        });
    },

    // 点击地图标记
    onMarkerTap(e) {
        const markerId = e.markerId;
        if (markerId === 0) return; // 客户标记不处理

        // 找到对应的配送员
        const selectedAunt = this.data.sortedAunts.find(aunt => aunt.id === markerId);
        if (selectedAunt) {
            this.setData({ selectedAunt });

            // 移动地图中心到选中的配送员位置
            this.setData({
                centerLongitude: selectedAunt.longitude,
                centerLatitude: selectedAunt.latitude
            });
        }
    },

    // 从列表中选择配送员
    selectAunt(e) {
        const id = e.currentTarget.dataset.id;
        const selectedAunt = this.data.sortedAunts.find(aunt => aunt.id === id);
        if (selectedAunt) {
            this.setData({ selectedAunt });

            // 移动地图中心到选中的配送员位置
            this.setData({
                centerLongitude: selectedAunt.longitude,
                centerLatitude: selectedAunt.latitude
            });
        }
    },

    // 切换排序方式
    changeSort(e) {
        const sorttype = e.currentTarget.dataset.sorttype;
        // 获取附近的配送员数据（模拟数据）

        this.setData({
            sorttype,
            // sortedAunts: this.sortAunts(this.data.aunts, sorttype)
        });
        this.getNearbyAunts(this.data.clientLocation, sorttype,this.data.city);
    },

    // 预览配送员照片
    previewPhotos(e) {
        const index = e.currentTarget.dataset.index;
        const aunt = this.data.sortedAunts[index];

        this.setData({
            showPhotoModal: true,
            currentAunt: aunt,
            currentPhotoIndex: 0
        });
    },

    // 关闭照片预览
    closePhotoModal() {
        this.setData({
            showPhotoModal: false
        });
    },

    // 切换侧滑窗口
    toggleSlidePanel() {
        this.setData({
            slidePanelOpen: !this.data.slidePanelOpen
        });
    },

    // 取消选择
    cancelSelect() {
        this.setData({ selectedAunt: null });
    },

    // 确认选择
    confirmSelect() {
        if (this.data.selectedAunt) {
            // 返回上一页并带回调结果
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.onAuntSelected) {
                getApp().globalData.Auntid = this.data.selectedAunt.accountId;
                prevPage.setData({
                    // activeStatus: 'taken',
                    caregiverId: this.data.selectedAunt.accountId
                })
                prevPage.onAuntSelected(this.data.selectedAunt);

            }

            wx.navigateBack();
        }
    },

    // 地图区域变化
    onRegionChange(e) {
        // 实际项目中可以在这里实现地图移动时重新加载配送员数据
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})